#include "gamewidget.h"
#include <QMessageBox>
#include <QTime>

GameWidget::GameWidget(QWidget *parent) : QWidget(parent) {
    gridSize = 20;       // 每个网格20x20像素
    isSpeedUp = false;
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(updateGame()));  // 旧式信号槽连接

    initGame();
    setFocusPolicy(Qt::StrongFocus);  // 允许接收键盘事件
}

// 初始化游戏状态
void GameWidget::initGame() {
    snake.clear();
    snake << QPoint(5, 5) << QPoint(4, 5) << QPoint(3, 5); // 初始蛇身
    direction = Right;
    QTime time = QTime::currentTime();
    qsrand(time.msec() + time.second() * 1000);  // 旧版随机数初始化
    generateFood();
    timer->start(200);  // 初始速度200ms
}

// 生成食物（避免与蛇身重叠）
void GameWidget::generateFood() {
    int maxX = width() / gridSize - 1;
    int maxY = height() / gridSize - 1;

    do {
        food.setX(qrand() % maxX);
        food.setY(qrand() % maxY);
    } while (snake.contains(food));
}

// 绘制游戏界面
void GameWidget::paintEvent(QPaintEvent *) {
    QPainter painter(this);

    // 绘制网格线
    painter.setPen(QColor(200, 200, 200));
    for (int x = 0; x < width(); x += gridSize)
        painter.drawLine(x, 0, x, height());
    for (int y = 0; y < height(); y += gridSize)
        painter.drawLine(0, y, width(), y);

    // 绘制蛇身（绿色方块）
    painter.setBrush(QColor(0, 180, 0));
    foreach (QPoint point, snake) {
        painter.drawRect(point.x() * gridSize,
                        point.y() * gridSize,
                        gridSize - 1,
                        gridSize - 1);
    }

    // 绘制食物（红色圆形）
    painter.setBrush(Qt::red);
    painter.drawEllipse(food.x() * gridSize,
                       food.y() * gridSize,
                       gridSize - 1,
                       gridSize - 1);
}

// 处理键盘输入
void GameWidget::keyPressEvent(QKeyEvent *event) {
    switch (event->key()) {
    case Qt::Key_W:
        if (direction != Down) direction = Up;
        break;
    case Qt::Key_S:
        if (direction != Up) direction = Down;
        break;
    case Qt::Key_A:
        if (direction != Right) direction = Left;
        break;
    case Qt::Key_D:
        if (direction != Left) direction = Right;
        break;
    case Qt::Key_Shift:
        timer->setInterval(isSpeedUp ? 200 : 100);  // 加速切换
        isSpeedUp = !isSpeedUp;
        break;
    }
}

// 游戏逻辑更新
void GameWidget::updateGame() {
    QPoint newHead = snake.first();

    // 计算新头部位置
    switch (direction) {
    case Up:    newHead.ry()--; break;
    case Down:  newHead.ry()++; break;
    case Left:  newHead.rx()--; break;
    case Right: newHead.rx()++; break;
    }

    // 碰撞检测
    if (newHead.x() < 0 || newHead.x() >= width() / gridSize ||
        newHead.y() < 0 || newHead.y() >= height() / gridSize ||
        snake.contains(newHead)) {
        gameOver();
        return;
    }

    snake.prepend(newHead);

    // 吃到食物检测
    if (newHead == food) {
        generateFood();
    } else {
        snake.removeLast();
    }

    update();  // 触发界面重绘
}

// 游戏结束处理
void GameWidget::gameOver() {
    timer->stop();
    QMessageBox::information(this, "游戏结束", "游戏结束，重新开始！");
    initGame();
}
